/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { Button, message } from 'antd';
import { ModalForm, ProFormRadio } from '@ant-design/pro-form';
import { useColumns, options } from './config/index';
import { getWarehouseList, getBrandList } from '@/services/exWarehouseRatio';
import { valueEnum } from './config/config';
import { handleDisable } from './utils';
import { outRateExport, closeBrandCollect } from '@/services/exWarehouseRatio';
import type { ActionType } from '@ant-design/pro-table';
import moment from 'moment';
import styles from './index.less';

const Index: React.FC = () => {
  const yesterday = moment().subtract(1, 'days');
  const actionRef = useRef<ActionType>();
  const [visible, setVisible] = useState(false);
  const [rowList, setRowList] = useState<any>([]);
  const [brand, setBrand] = useState<string>('yt');
  const [rateType, setRateType] = useState<string>('1');
  const [searchDate, setSearchDate] = useState<any[]>([yesterday, yesterday]);
  const [keyWords, setKeyWords] = useState<string>('');
  const [rowKeys, setRowKeys] = useState<any[]>([]);
  const [brandList, setBrandList] = useState<any>(valueEnum);

  const handleRequest = async (params: any) => {
    const { current: page, pageSize } = params;
    setRowKeys([]);
    setRowList([]);
    if (searchDate && searchDate.length) {
      params.date_from = moment(searchDate[0]).format('YYYY-MM-DD');
      params.date_to = moment(searchDate[1]).format('YYYY-MM-DD');
    }
    params.page = page;
    params.size = pageSize;
    delete params.date;
    delete params.current;
    delete params.pageSize;
    return getWarehouseList(params);
  };

  const onSubmit = (values: any) => {
    let data = rowList.map((item: any) => ({ cm_id: item.cm_id, brand: item.brand }));
    let cm_id: any = [];
    if (values.radio !== '1') {
      cm_id = rowList.map((item: any) => item.cm_id);
      data = [];
    } else {
      closeBrandCollect({
        data,
        cm_id,
        is_close: 2,
        admin_sms: 0,
      }).then(({ code, msg }) => {
        if (code == 0) {
          message.success(msg);
          actionRef.current?.reload(false);
          setVisible(false);
        } else {
          message.error(msg);
        }
      });
      return;
    }
    handleDisable({
      data,
      cm_id,
      options: values.radio,
      actionRef,
      cb: () => {
        setVisible(false);
      },
    });
  };

  const openUpgrade = () => {
    const innList = rowList.map((item: any) => item.cm_id);
    if (innList.length <= 0) {
      message.error('批量升级需至少选择一项');
      return;
    }
    setVisible(true);
  };

  const selectChange = (_: any, rowLists: any) => {
    setRowKeys(_);
    setRowList(rowLists);
  };

  const handleExcel = () => {
    let requestData: any = {
      brand,
      rate_type: rateType,
      keywords: keyWords,
    };
    if (searchDate && searchDate.length > 1) {
      const [date_from, date_to] = searchDate;
      requestData = {
        ...requestData,
        date_from: moment(date_from).format('YYYY-MM-DD'),
        date_to: moment(date_to).format('YYYY-MM-DD'),
      };
    }
    outRateExport(requestData).then((res: any) => {
      const { code, data, msg } = res;
      if (code == 0) {
        window.open(data, '_black');
      } else {
        message.error(msg);
      }
    });
  };

  const columns = useColumns(
    actionRef,
    { setBrand, setRateType, setSearchDate, setKeyWords },
    brand,
    brandList,
  );

  useEffect(() => {
    getBrandList().then(({ data }: any) => {
      let brands = {};
      Object.keys(data)
        .map((item: any, index: number) => ({
          [item]: {
            text: Object.values(data)[index],
            status: item,
          },
        }))
        .forEach((item: any) => {
          brands = Object.assign(brands, item);
        });
      setBrandList(brands);
    });
  }, []);

  return (
    <>
      <ProTable<any>
        actionRef={actionRef}
        rowKey='id'
        request={handleRequest}
        columns={columns}
        className={styles.table}
        pagination={{
          pageSize: 30,
          showQuickJumper: false,
          showSizeChanger: false,
        }}
        options={false}
        search={{
          collapsed: false,
          optionRender: (_, { form }) => [
            <Button
              key='phone'
              type='primary'
              onClick={() => {
                form?.submit?.();
              }}
            >
              搜索
            </Button>,
            <Button key='1' type='primary' onClick={handleExcel}>
              导出
            </Button>,
            <Button key='12' type='primary' onClick={openUpgrade}>
              批量处理
            </Button>,
          ],
        }}
        rowSelection={{
          type: 'checkbox',
          selectedRowKeys: rowKeys,
          onChange: selectChange,
          hideSelectAll: false,
        }}
      />
      <ModalForm<{
        name: string;
        company: string;
      }>
        title='处理方式'
        visible={visible}
        width={400}
        onFinish={onSubmit}
        modalProps={{
          onCancel: () => setVisible(false),
        }}
        initialValues={{
          radio: '1',
        }}
      >
        <ProFormRadio.Group name='radio' options={options} />
      </ModalForm>
    </>
  );
};

export default Index;
